/**
 * Created by limei on 2018/6/12.
 */
import MYCONF from '../../myconf'
import eventBus from '../../util/event-bus'
import MapHelper from '../../util/map-helper'
import env from '../../util/env'

export default class mapHandler {
  constructor(_view) {
    this._view = _view;
    this.map = _view.map;
    this.popups = [];
  }

  loadImages(callback) {
    const map = this.map;
    let mapIMgs = ['chuzu.png', 'chengji.png', 'shengji.png', 'gongjiao.png', 'huoche.png', 'kache.png', 'lvyou.png', 'start.png', 'end.png','car-1.png','car-2.png','car-3.png','car-4.png','car-5.png','car-6.png', 'redring.png', 'warncar.png'];
    for(let i=1;i<15;i++){
      let item = 'icon-'+i+'.png'
      let imgUrl = './static/images/infrastructure/icon-'+i+'.png';
      map.loadImage(imgUrl, function (error, image) {
        if (error) throw error;
        map.addImage(item.split(".")[0], image);
      })
    }

    let count = 0;

    mapIMgs.map((item) => {
      let imgUrl = './static/images/map/' + item;
      map.loadImage(imgUrl, function (error, image) {
        if (error) throw error;
        map.addImage(item.split(".")[0], image);
        if (callback && ++count >= mapIMgs.length) {
          callback();
        }
      })
    });
  }

  setMapEvent(){
    const map = this.map;
    const _this = this;
    map.on('click', function (e) {
      if (_this._view.home_state=== 'realtime') {
        if (!map.getLayer('real-custom')) return;
        let points = map.queryRenderedFeatures(e.point, {
          sourceLayer: 'real-custom',
        });
       /* console.log('points', points);*/

        if (!map.getLayer('real-icon')) return;
        //非活跃点
        let feas = map.queryRenderedFeatures(e.point, {
          layers: ['real-icon']
        });
        /*console.log('fes', feas);*/
        if (!feas.length) return;
        const carId = feas[0].properties.carid;
        // _this._view.updateSingleCar({id:carId});
        let real_coordinate = feas[0].geometry.coordinates;
        //改为弹框跟踪
        _this._view.$http.get(MYCONF.service.searchCarInfo+carId)
          .then(response => {
            response = response.body;response
            _this._view.updateSingleCar(response);
            let realPopup = new minemap.Popup({closeOnClick: true, offset: [0, -30]})
              .setLngLat(real_coordinate)
              .setDOMContent(MapHelper.addCarTrackPopup(response))
              .addTo(map);
            env.popups.push(realPopup);
            _this._view.updateIsMainPopShow(false);
            document.getElementById(_this._view.single_car.id).onclick=function(){
              _this._view.updateHomeState("realtime_single");
              env.popups.map((item) => {
                item.remove();
              })
            };
          }, response => {
            // error callback
          });
      }

      if (_this._view.home_state==='company_group') {
        if (!map.getLayer('group-icon')) return;
        //非活跃点
        let feas = map.queryRenderedFeatures(e.point, {
          layers: ['group-icon']
        });
        console.log('fes', feas);
        if (!feas.length) return;
        const carId = feas[0].properties.carid;
        _this._view.updateSingleCar({id:carId});
        const group_coordinate = feas[0].geometry.coordinates;
        //改为弹框跟踪
        _this._view.$http.get(MYCONF.service.searchCarInfo+carId)
          .then(response => {
            response = response.body;
            _this._view.updateSingleCar(response);
            let groupPopup = new minemap.Popup({closeOnClick: true, offset: [0, -30]})
              .setLngLat(group_coordinate)
              .setDOMContent(MapHelper.addCarTrackPopup(response))
              .addTo(map);
            env.popups.push(groupPopup);

            document.getElementById(_this._view.single_car.id).onclick=function(){
              _this._view.updateHomeState("realtime_single");
              env.popups.map((item) => {
                item.remove();
              })
            };
          }, response => {
            // error callback
          });
        // _this._view.updateHomeState("realtime_single");
        // const coordinate = feas[0].geometry.coordinates;
      }

      if(_this._view.home_state==='alarm_info'){
        if (!map.getLayer('single-car')) return;
        //非活跃点
        let feas = map.queryRenderedFeatures(e.point, {
          layers: ['single-car']
        });
        console.log('fes', feas);
        if (!feas.length) return;
        const single_coordinate = feas[0].geometry.coordinates;
        let singlePopup = new minemap.Popup({closeOnClick: true, offset: [0, -30]})
          .setLngLat(single_coordinate)
          .setDOMContent(MapHelper.addCarTrackPopup(_this._view.single_car))
          .addTo(map);
        env.popups.push(singlePopup);

        document.getElementById(_this._view.single_car.id).onclick=function(){
          _this._view.updateHomeState("realtime_single");
          env.popups.map((item) => {
            item.remove();
          })
        };
      }

      if (_this._view.cur_nav==='2') {
        if (!map.getLayer('city-icon')) return;
        //非活跃点
        let feas = map.queryRenderedFeatures(e.point, {
          layers: ['city-icon']
        });
        const city_coordinate = feas[0].geometry.coordinates;
        if (!feas.length) return;
        let cityPopup = new minemap.Popup({closeOnClick: true, offset: [22, -30]})
          .setLngLat(city_coordinate)
          .setDOMContent(MapHelper.addCityMapPopup(feas[0].properties))
          .addTo(map);
        env.popups.push(cityPopup);
        _this._view.updateIsPopShow(false);
        _this._view.updateIsTwoPop(false);
      }
    });

    map.on("mousemove",function(e){
      let feature0= map.queryRenderedFeatures(e.point, {
        layers: ['real-icon']
      });
      let feature1 = map.queryRenderedFeatures(e.point, {
        layers: ['group-icon']
      });
      let feature2 = map.queryRenderedFeatures(e.point, {
        layers: ['city-icon']
      });
      let feature3 = map.queryRenderedFeatures(e.point, {
        layers: ['single-car']
      });
      if (feature0 && feature0.length > 0) {
        map.getCanvas().style.cursor = 'pointer';
      }
      if (feature1 && feature1.length > 0) {
        map.getCanvas().style.cursor = 'pointer';
      }
      if (feature2 && feature2.length > 0) {
        map.getCanvas().style.cursor = 'pointer';
      }
      if (_this._view.home_state==='alarm_info' && feature3 && feature3.length > 0) {
        map.getCanvas().style.cursor = 'pointer';
      }
    })
  }

  setSpeedMarker(){
    let el = document.createElement('div');
    env.speed_el = el;
    el.id = 'speed_marker';
    el.style["background-image"] = "url(\'./static/images/index/pop.png\')";
    // el.style["background-color"] = "#131721";
    el.style["background-repeat"] = "no-repeat";
    el.style.width = "60px";
    el.style.height = "32px";
    el.style["background-size"] = "contain";
    el.style["line-height"] = "26px";
    el.style.position = "absolute";
    el.style.cursor = "pointer";
    env.speedMarker =new minemap.Marker(el, {offset: [-66, -48]});
    return el;
  }

  //删除所有已添加图层
  removeAllLayers() {
    const layerList = [
      'single-car',
      'history-path',
      'whole-path',
      'startSymbol',
      'endSymbol',
      'real-custom',
      'real-path',
      'real-icon',
      'real-group',
      'group-icon',
      'city-icon',
      'real-warn-circle',
      'real-warn-icon',
      'history-heatmap0', 'history-heatmap1', 'history-heatmap2', 'history-heatmap3', 'history-heatmap4', 'history-heatmap5', 'history-heatmap6', 'history-heatmap7', 'history-heatmap8', 'history-heatmap9', 'history-heatmap10', 'history-heatmap11', 'history-heatmap12', 'history-heatmap13', 'history-heatmap14', 'history-heatmap15', 'history-heatmap16', 'history-heatmap17', 'history-heatmap18', 'history-heatmap19', 'history-heatmap20', 'history-heatmap21', 'history-heatmap22', 'history-heatmap23',
    ];
    const map = this.map;
    layerList.map((item) => {
      if (map.getSource(item)) {
        map.removeSource(item)
      }
      if (map.getLayer(item)) {
        map.removeLayer(item)
      }
    })
  }



  removeCarPopups(){
    env.popups.map((item) => {
      item.remove();
    });
    if(env.speedMarker) env.speedMarker.remove();
  }

  updateSpeedMarker(lngLat, text) {
    //console.log("速度是:",text);
    env.speed_el.innerText = text + 'km/h';
    env.speedMarker.setLngLat(lngLat).addTo(this._view.map);
  }

}
